﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using TTGame;

/*
 * ObjRecycler
 *
 * 对象自动回收。注，回收的是整个Gameobject
 *
 * 回收条件：
 *      时间
 *
 * 自行确保：
 *     对象由ObjectRecycler创建
 *
 *
 * 依赖：
 *
 * ！不写重复代码！
 * @author TTun
 * @date 10/10/2017 10:02:51 AM
 */
namespace TTGameEngine {

public class ObjRecycleTimer : MonoBehaviour {
    [Tooltip("<=0 或者 >=999，将默认是循环粒子，不倒计时。")]
    public float lifeTime;
    [SerializeField, ReadOnly]
    float t_lifeTime;
    [SerializeField, ReadOnly]
    bool isLoop = false;
    int m_recycleID = -1;

    public int RecycleID {
        get {
            if(m_recycleID == -1) {
                m_recycleID = Random.Range(1, int.MaxValue);
            }
            return m_recycleID;
        }
    }

    public float LifeTime {
        set {
            lifeTime = value;
            reset();
        }

        get {
            return lifeTime;
        }
    }

    // Update is called once per frame
    void Update() {
        if(isLoop) return;

        float dt = Time.deltaTime;
        t_lifeTime -= dt;
        if(t_lifeTime <= 0) {
            RecycleObj();
        }

    }

    public void reset() {
        if(lifeTime <= 0 || lifeTime >= 999) {
            isLoop = true;
        } else {
            isLoop = false;
        }
        t_lifeTime = lifeTime;
    }

    void OnEnable() {
        reset();
    }

    //注意：回收的是整个对象，而非脚本。所以，自行保证对象是由ObjectRecycle创建出来的。
    void RecycleObj() {
        ObjectRecycler.Instance.Deactivate(gameObject);
        m_recycleID = -1;
    }


    /// <summary>
    /// 回收对象可能会被多个对象引用。为了防止前一个引用对象调用，添加ID检测。
    /// </summary>
    /// <param name="recycleID"></param>
    public void RecycleObjSafe(int recycleID) {
        if(recycleID == m_recycleID) {
            RecycleObj();
        }
    }

}

}
